<template>
  <view class="my-coupon">
    <u-line color="#f6f6f6"></u-line>
    <!-- 顶部tab -->
    <view class="tab-box">
      <u-tabs-swiper
        ref="uTabs"
        :list="list"
        :current="current"
        @change="tabsChange"
        :is-scroll="false"
        active-color="#333"
        inactive-color="#666"
        swiperWidth="750"
        bar-width="80"
        :bar-style="barActiveStyle"
      ></u-tabs-swiper>
    </view>

    <view class="content">
      <swiper
        class="swiper"
        :current="swiperCurrent"
        :duration="300"
        @transition="transition"
        @animationfinish="animationfinish"
      >
        <swiper-item
          class="swiper-item"
          v-for="(item, index) in result"
          :key="index"
        >
          <scroll-view class="scroll-view" scroll-y @scrolltolower="onLoadmore">
            <u-empty
              mode="coupon"
              v-if="item.data.length <= 0 && item.isEnd"
              :text="current ? '暂无套餐卡' : '暂无优惠券'"
            ></u-empty>
            <view style="overflow: hidden" v-else>
              <view v-for="(i, k) in item.data" :key="k">
                <coupon-item
                  @click="jumpPage"
                  :item="i"
                  :type="result[index].couponClass"
                  v-if="!i.is_Package"
                />
                <set-meal-item @click="jumpPage" :item="i" v-else />
              </view>

              <view class="loading-status"
                ><u-loadmore :status="item.status"
              /></view>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script>
import couponItem from './components/couponItem.vue' // 优惠券列表组件
import setMealItem from './components/setMealItem.vue' // 套餐列表组件
export default {
  components: {
    couponItem,
    setMealItem,
  },
  data() {
    return {
      barActiveStyle: {
        background: 'linear-gradient(0deg, #FBB000, #FFE23E)',
      }, // tab选中是下划线样式
      list: [
        {
          name: '优惠券',
        },
        {
          name: '套餐卡',
        },
      ], // tab数据列表
      current: 0, // tabs组件的current值
      swiperCurrent: 0, // swiper组件的current值
      result: [
        {
          couponClass: 2,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: [],
        },
        {
          couponClass: 4,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: [],
        },
      ],
      // 请求优惠券金额的接口参数
      params: {
        discountTotalAmount: 0,
        selectedCouponId: '',
        selectedCouponDetailsId: '',
        goodsList: [],
        serviceFeeList: [],
      },
      from: '', // 页面来源 用于点击套餐判断，如果没有值就跳转详情页
      mobile: '', // 用户手机号
    }
  },

  computed: {
    orderGoodsList() {
      return this.$store.state.afterSales.orderGoodsList
    },

    orderServiceList() {
      return this.$store.state.afterSales.orderServiceList
    },
  },

  onLoad(option) {
    this.current = Number(option.status) || 0
    this.swiperCurrent = Number(option.status) || 0
    this.from = option.from || ''
    this.mobile = !'13056699958' || this.$store.state.afterSales.arrvialPhone
    this.getList()
    // 监听订单详情的事件
    uni.$once('orderDetailChange', this.handlePageData)
  },
  methods: {
    // 点击tan切换
    tabsChange(index) {
      this.swiperCurrent = index
      this.getList()
    },
    transition(e) {
      let dx = e.detail.dx
      this.$refs.uTabs.setDx(dx)
    },
    animationfinish(e) {
      let current = e.detail.current
      this.$refs.uTabs.setFinishCurrent(current)
      this.swiperCurrent = current
      this.current = current
      this.getList()
    },
    // 禁用swiper滑动
    stopTouchMove() {
      return false
    },
    onLoadmore() {
      this.getList()
    },

    // 处理订单页面带过来的数据
    handlePageData(res) {
      this.params = {
        discountTotalAmount: res.discountTotalAmount,
        selectedCouponId: '',
        selectedCouponDetailsId: '',
        goodsList: res.products.map((item) => ({
          maintenance_Type_Id: item.goodsTypeId,
          maintenance_Goods_Id: item.productId,
          sale_Price: item.productPrice,
          coupon_Details_Id: item.couponId,
          coupon_Id: null,
          discountAmount: item.couponMoney,
          productName: item.productName,
          remark: null,
          costPrice: item.inPrice,
          rateIncrease: item.addRange,
          count: item.productCount,
        })),
        serviceFeeList: res.serveList.map((item) => ({
          service_Price: item.servicePrice,
          service_Name: item.serviceName,
          maintenance_Type_Id: item.serviceId,
          coupon_Details_Id: item.couponId,
          coupon_Id: null,
          discountAmount: item.couponMoney,
          serviceCount: item.serviceCount,
        })),
      }
      console.log('参数', this.params)
    },

    // 跳转页面
    async jumpPage(params) {
      if (params.data.is_Package) {
        this.params.selectedCouponId = params.data.id
        uni.navigateTo({
          url:
            '/pages_afterSales/selectSetMenu/selectSetMenu?packageId=' +
            params.data.id,
        })
      } else {
        this.$api.afterSales
          .getUsableCouponsByIdAndGoods({
            id: params.data.id,
            car_num: this.$store.state.afterSales.carInfo.carbrand,
            goodsList: this.orderGoodsList,
            serviceFeeList: this.orderServiceList,
          })
          .then((res) => {
            let data = res.data
            let total = 0
            let arr = []
            let status = false
            data.groupList.map((item) => {
              item.goodsServiceList.map((i) => {
                if (i.isUsable) {
                  total += Number(-i.discountAmount)
                  res.data.coupon.coupon_Id = i.coupon_Id
                  res.data.coupon.coupon_Details_Id = i.coupon_Details_Id
                }
                arr.push(i)
              })
            })
            status = arr.some((item) => {
              return item.isUsable
            })
            console.log(res.data)
            if (status) {
              uni.$emit('couponChange', {
                coupon: res.data.coupon,
                discountTotalAmount: total,
                type: 1,
              })
              uni.navigateBack({
                delta: 1,
              })
            } else {
              uni.showToast({
                icon: 'none',
                title: '对不起，无法使用该优惠券',
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
        // try {
        //   this.params.selectedCouponDetailsId = params.data.cid
        //   console.log('请求参数', params.data)
        //   const res = await this.$api.afterSales.CheckCouponsByGoods(
        //     this.params
        //   )
        //   uni.navigateBack({
        //     animationDuration: 0,
        //   })
        //   uni.$emit('couponChange', {
        //     data: res.data,
        //     coupon: params.data,
        //     type: params.type,
        //   })
        // } catch (e) {
        //   //TODO handle the exception
        // }
      }
    },
    // 计算总共有多少页
    pageCount(totalnum, limit) {
      return totalnum > 0
        ? totalnum < limit
          ? 1
          : totalnum % limit
          ? parseInt(totalnum / limit) + 1
          : totalnum / limit
        : 0
    },
    // 获取列表数据
    async getList(type) {
      let list = this.result[this.swiperCurrent]
      if (type) {
        list.PageIndex = 1
        list.isEnd = false
        list.loading = false
        list.status = 'loading'
      }
      if (list.loading || list.isEnd) {
        return false
      }
      list.loading = true
      this.$set(this.result, this.swiperCurrent, list)
      try {
        let res = await this.$api.afterSales.GetCouponList({
          coupon_class: list.couponClass,
          pageIndex: list.PageIndex,
          pageSize: list.PageSize,
          mobile: this.mobile,
        })

        let couponlist = res.data.list
        if (type) {
          list.data = []
        }

        if (
          couponlist.length <= 0 ||
          list.PageIndex >= this.pageCount(res.data.total, list.PageSize)
        ) {
          list.isEnd = true
          list.status = 'nomore'
        }

        if (couponlist.length > 0) {
          list.data = list.data.concat(couponlist)
          list.PageIndex = list.PageIndex + 1
        }
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      } catch (e) {
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }
    },
  },
}
</script>

<style>
page {
  background-color: #f6f6f6;
}
</style>

<style lang="scss">
page {
  height: 100%;
}
.my-coupon {
  height: 100%;
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    overflow: hidden;
  }
  .swiper,
  .swiper-item,
  .scroll-view {
    height: 100%;
  }
  .loading-status {
    padding: 40rpx 0;
  }
  .coupon-item:last-child {
    margin-bottom: 0 !important;
  }
}
</style>
